﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using NetCoreCMS.Common;
using NetCoreCMS.IServices;

namespace NetCoreCMS.Web.Areas.WebApi.Controllers
{
    /// <summary>
    /// 只搜商品
    /// </summary>
    public class Get_SearchController : BaseController
    {
        public IArticleService _article { get; set; }
        public IShopService _shop { get; set; }
        [HttpGet]
        public IActionResult Get(int page = 1, int page_size = 20, string keywords="")
        {
            if(string.IsNullOrEmpty(keywords))
            {
                return Ok(new { status = 0, msg = "搜索内容不为空！" });
            }
            if (!Utils.IsSafeSqlString(keywords))
            {
                return Ok(new { status = 0, msg = "搜索内容不正确！" });
            }
            page = page > 0 ? page : 1;
            string strwhere = "where status=0 and title like '%"+keywords+"%'";
            var list = _article.GetList(1, page_size*100, strwhere, "add_time desc,id desc");
            string shopwhere = "where is_lock=0 and shopname like '%" + keywords + "%'";
            var list2= _shop.GetList(1, page_size*100, shopwhere, "add_time desc,id desc");
            int totalcount = list.Count+list2.Count;
            int pageCount = totalcount / page_size;
            if (pageCount < 1)
            {
                pageCount = 1;
            }
            if (totalcount % page_size > 0)
            {
                pageCount += 1;
            }
            if (pageCount <= 1)
            {
                pageCount = 1;
            }
            var sys = Common.XMLConfig.Sysconfig.loadConfig(_env.ContentRootPath);
            List<DTO.Search> dtos = new List<DTO.Search>();
            foreach (var item in list)
            {
                DTO.Search dto = new DTO.Search();
                dto.id = item.id;
                dto.title = item.title;
                dto.img_url = sys.weburl + item.img_url;
                dto.sell_price = item.sell_price;
                dto.ftype = item.channel_id;
                dtos.Add(dto);
            }
            foreach (var item in list2)
            {
                DTO.Search dto = new DTO.Search();
                dto.id = item.id;
                dto.title = item.shopname;
                dto.img_url = sys.weburl + item.img_url;
                dto.sell_price = 0;
                dto.ftype = 3;
                dtos.Add(dto);
            }
            return Ok(new { status = 1, list = dtos.Skip((page-1)*page_size).Take(page_size).ToList(), page = page, page_count = pageCount, total_count = totalcount });
        }
    }
}